package com.wjk.easy.ui;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.wjk.easy.R;
import com.wjk.easy.adapter.DataManageListAdapter;
import com.wjk.easy.db.Exam;
import com.wjk.easy.db.ExamData;
import com.wjk.easy.db.LastUserBean;
import com.wjk.easy.utils.D;
import com.wjk.easy.view.RecycleViewDivider;

import java.util.ArrayList;
import java.util.List;

public class DataManageActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_data_manage_list);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();//返回
            }
        });
        initView();
        initData();
    }

    RecyclerView listview;
    DataManageListAdapter mAdapter;
    private ProgressBar loadingProgressBar;
    private void initView() {
        listview = findViewById(R.id.rv_list);
        // 定义一个线性布局管理器
        LinearLayoutManager manager = new LinearLayoutManager(this);
        // 设置布局管理器
        listview.setLayoutManager(manager);
        listview.addItemDecoration(new RecycleViewDivider(
                this, LinearLayoutManager.VERTICAL, 1, getResources().getColor(R.color.colorLightTrans)));
        loadingProgressBar = findViewById(R.id.loading);
    }

    LastUserBean currentUser;

    private void initData() {
        currentUser = D.queryCurrentUser(this);
        if (currentUser != null) {
            List<Exam> examList = D.queryExamList(currentUser.getUserId());
            if (examList.size() < 1) {
                showNoData();
            } else {
                int[] countArr = new int[examList.size()];
                for (int i = 0; i < examList.size(); i++) {
                    List<ExamData> examDatas = D.queryDataCountByExamId(examList.get(i).getId(), currentUser.getUserId());
                    countArr[i] = examDatas.size();
                }
                initAdapter(examList, countArr);
            }
        }
    }

    private void initAdapter(List<Exam> examList, int[] countArr) {
        mAdapter = new DataManageListAdapter(this, examList, countArr);
        mAdapter.setEmptyListener(new DataManageListAdapter.EmptyListener() {
            @Override
            public void onEmpty() {
                showNoData();
            }

            @Override
            public void onExportClick(Exam exam) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                        showTipDialog();
                    } else {
                        doExport(exam);
                    }
                } else {
                    doExport(exam);
                }
            }
        });
        listview.setAdapter(mAdapter);
    }

    private void doExport(Exam exam){
        LastUserBean currentUser = D.queryCurrentUser(DataManageActivity.this);
        if (currentUser != null) {
            loadingProgressBar.setVisibility(View.VISIBLE);
            D.exportData(exam, DataManageActivity.this, currentUser, new D.onExportCompeteListener() {
                @Override
                public void onComplete(String filePath, int dataCount) {
                    loadingProgressBar.setVisibility(View.GONE);
                    String title="导出成功";
                    String msg = "本次共导出"+dataCount+"条数据，"+"保存在："+filePath;
                    showComplete(title,msg);
                }

                @Override
                public void onFail(String errMsg) {
                    loadingProgressBar.setVisibility(View.GONE);
                    String title="导出失败";
                    String msg = errMsg;
                    showComplete(title,msg);
                }
            });
        }
    }

    private void showNoData() {
        listview.setVisibility(View.GONE);
        findViewById(R.id.tv_no_data_tip).setVisibility(View.VISIBLE);
    }

    private void showHaveData() {
        listview.setVisibility(View.VISIBLE);
        findViewById(R.id.tv_no_data_tip).setVisibility(View.GONE);
    }

    private void showComplete(String title, String msg) {
        new AlertDialog.Builder(this)
                .setTitle(title)
                .setMessage(msg)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                /*.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })*/
                .show();
    }

    private void showTipDialog() {
        new AlertDialog.Builder(this)
                .setTitle("开启本地文件相关的权限")
                .setMessage("为了能导出您的数据，请在接下来的弹窗中点击同意")
                .setCancelable(false)
                .setPositiveButton("知道了", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        getPermissions();
                    }
                }).show();
    }


    private final int SDK_PERMISSION_REQUEST = 127;

    @TargetApi(23)
    private void getPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ArrayList<String> permissions = new ArrayList<>();
            /***
             * 定位权限为必须权限，用户如果禁止，则每次进入都会申请
             */
            // 定位精确位置
            /*if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
            }
            if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);
            }*/
            /*
             * 读写权限和电话状态权限非必要权限(建议授予)只会申请一次，用户同意或者禁止，只会弹一次
             */
            // 读写权限
            addPermission(permissions, Manifest.permission.WRITE_EXTERNAL_STORAGE);

            // 读取电话状态权限
            /*if (addPermission(permissions, Manifest.permission.READ_PHONE_STATE)) {
                permissionInfo += "Manifest.permission.READ_PHONE_STATE Deny \n";
            }*/

            if (permissions.size() > 0) {
                requestPermissions(permissions.toArray(new String[permissions.size()]), SDK_PERMISSION_REQUEST);
            }
        }
    }


    @TargetApi(23)
    private boolean addPermission(ArrayList<String> permissionsList, String permission) {
        if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) { // 如果应用没有获得对应权限,则添加到列表中,准备批量申请
            if (shouldShowRequestPermissionRationale(permission)) {
                return true;
            } else {
                permissionsList.add(permission);
                return false;
            }

        } else {
            return true;
        }
    }

    @TargetApi(23)
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}
